package com.cykj.pos.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.date.DateUtil;
import com.cykj.pos.controller.api.PosV1TransactioNotice;
import com.cykj.pos.domain.*;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.mapper.BizPosMachineStatusRecordsMapper;
import com.cykj.pos.mapper.BizXYFInfoMapper;
import com.cykj.pos.mapper.UnFailureActiveTemplateMapper;
import com.cykj.pos.service.*;
import com.cykj.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 许晓龙
 * @date 2024/8/14 10:00
 */
@Service
public class BizXYFInfoServiceImpl extends ServiceImpl<BizXYFInfoMapper, BizXYFInfo> implements IBizXYFService {

    @Resource
    private IBizPosMachineService posMachineService;
    @Resource
    private IBizMerchantService bizMerchantService;
    @Resource
    private BizPosMachineMapper bizPosMachineMapper;
    @Resource
    private IBizMerchantInfoService bizMerchantInfoService ;
    @Resource
    private BizPosMachineStatusRecordsMapper bizPosMachineStatusRecordsMapper;
    @Resource
    private PosV1TransactioNotice posV2TransactioNotice;

    @Resource
    private  IBizPosMachineService bizPosMachineService;

    @Resource
    private IBizFeesChargedService bizFeesChargedService;

    @Resource
    private  IBizTransactionAmount bizTransactionAmount;

    @Resource
    private IPosTransactionNoticeService iPosTransactionNoticeService;
    @Resource
    private IBizMerchantService iBizMerchantService;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private UnFailureActiveTemplateMapper unFailureActiveTemplateMapper;

    @Resource
    private IAizUnActiveRecordsService iAizUnActiveRecordsService;


    @Override
    public AjaxResult xyfInfo(JSONObject data) throws ParseException {
        System.out.println("接收绑定通知"+data.toJSONString());
        String termno = data.getString("termno");// 终端号
        String termphyno = data.getString("termphyno");// 终端机身号
        String agentid = data.getString("agentid");// 代理商编号
        String mercid = data.getString("mercid"); // 绑定商户号
        String terminalId = data.getString("terminalId");// 逻辑终端号
        String policyid = data.getString("policyid");// 机具政策编号
        String merextdat = data.getString("merextdat");// 绑定日期yyyyMMdd
        String mercname = data.getString("mercname");// 商户名称
        String applydat = data.getString("applydat");// 注册日期
        String status = data.getString("status");// 商户状态0开通 3审核中 1关停 6注销(即关停) 7暂停(即关停)
        String apptype = data.getString("apptype");// 应用类型00:星通 01:陆POS 03:小陆
        String name = data.getString("name");// 商户姓名
        String idcard = data.getString("idcard");// 身份证号
        //查询设备信息
        BizPosMachine machine = posMachineService.selectPosBySnCode(termphyno);
        BizChannel channelDataByChannel = bizMerchantInfoService.getChannelDataByChannel(machine.getChannel());
        BizMerchant merchantByMerchId = iBizMerchantService.selectBizMerchantBySN(termphyno);
        SysUser sysUser = sysUserService.selectUserById(merchantByMerchId.getUserId());
        BizMerchantInfo bizMerchantInfo=new BizMerchantInfo();
        BizMerchantInfo merchantInfoBySn = bizMerchantInfoService.getMerchantInfoBySn(termphyno);
        if (merchantInfoBySn != null){
            bizMerchantInfo.setId(merchantInfoBySn.getId());
        }
        BizPosMachineStatusRecords bizPosMachineStatusRecords1 = bizPosMachineStatusRecordsMapper.selectBizPosMachineStatusRecordsBysnCode(termphyno);
        if (bizPosMachineStatusRecords1 == null){
            BizPosMachineStatusRecords bizPosMachineStatusRecords=new BizPosMachineStatusRecords();
            bizPosMachineStatusRecords.setSnCode(termphyno);
            bizPosMachineStatusRecords.setMerchantId(mercid);
            bizPosMachineStatusRecords.setTime(merextdat);
            bizPosMachineStatusRecords.setName(name);
            //新增激活表信息
            bizPosMachineStatusRecordsMapper.insertBizPosMachineStatusRecords(bizPosMachineStatusRecords);
        }
        bizMerchantInfo.setInfoCompleted("1");
        bizMerchantInfo.setAuditStatus("3");
        bizMerchantInfo.setPosCode(termphyno);
        bizMerchantInfo.setMerchantName(name);
        bizMerchantInfo.setMerchantShortHand(name);
        bizMerchantInfo.setLegalPersonName(name);
        bizMerchantInfo.setMerchId(merchantByMerchId.getMerchId());
        bizMerchantInfo.setMerchantCode(mercid);
        bizMerchantInfo.setRegisterTime(applydat);
        bizMerchantInfo.setWhetherBinding("1");
        bizMerchantInfo.setOnLine("0");
        bizMerchantInfo.setCertificateNo(idcard);
        bizMerchantInfo.setSn(terminalId);
        bizMerchantInfo.setDeptId(sysUser.getDeptId());
        bizMerchantInfo.setUserId(sysUser.getUserId());
        bizMerchantInfo.setChannel(machine.getChannel());
        bizMerchantInfo.setChannelName(channelDataByChannel.getChannelName());
        //存到自己的库里
        boolean save = bizMerchantInfoService.saveOrUpdate(bizMerchantInfo);
//        if(machine.getTemp1() != null){
//            UnFailureActiveTemplate unFailureActiveTemplate = unFailureActiveTemplateMapper.selectById(machine.getTemp1());
//            if(unFailureActiveTemplate != null){
//                // 增加一条未激活记录
//                AizUnActiveRecords aizUnActiveRecords = new AizUnActiveRecords();
//                aizUnActiveRecords.setMerchId(merchantByMerchId.getMerchId());
//                aizUnActiveRecords.setMerchName(sysUser.getNickName());
//                aizUnActiveRecords.setMerchantCode(mercid);
//                aizUnActiveRecords.setMerchantName(name);
//                aizUnActiveRecords.setMerchPhone(sysUser.getPhonenumber());
//                aizUnActiveRecords.setBindTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(merextdat));
//                aizUnActiveRecords.setPosSn(terminalId);
//                aizUnActiveRecords.setTempDays(unFailureActiveTemplate.getDays());
//                aizUnActiveRecords.setDays(0);
//                aizUnActiveRecords.setCreateTime(DateUtil.getBaiDuTime());
//                iAizUnActiveRecordsService.saveOrUpdate(aizUnActiveRecords);
//            }else{
//                System.out.println("SN"+terminalId+"绑定时未查询到未激活模板");
//            }
//        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult xyfSim(JSONObject data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LambdaQueryWrapper<BizMerchantInfo> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BizMerchantInfo::getMerchantCode,data.getString("mercid"));
        BizMerchantInfo one = bizMerchantInfoService.getOne(lambdaQueryWrapper);
        String posSn = one.getPosCode();
        String receivefee = data.getString("receivefee");
        if(data.getString("receivefee").contains(".")){
            String[] receivefees = data.getString("receivefee").split("\\.");
            receivefee = receivefees[0];
        }
        //发放流量费
        SynchronizationDataDTO sy = new SynchronizationDataDTO();
        sy.setSim_amt(Integer.parseInt(receivefee));
        sy.setAmnount(Double.parseDouble(receivefee));
        sy.setPos_sn(posSn);
        sy.setHost_date(sdf.format(new Date()));
        sy.setMerchant_no(data.getString("mercid"));
        sy.setHost_ret_code("00");
        sy.setChannel("16");
        sy.setTrans_type(293);
        sy.setOrder_no(IdWorker.getIdStr());
        iPosTransactionNoticeService.simFee(sy);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult xyfUnbind(JSONObject data) {
        String termphyno = data.getString("termphyno");
        bizMerchantInfoService.deleteBySN(termphyno);
        //删除激活表信息
        bizPosMachineStatusRecordsMapper.deleteBizPosRecordsNew(termphyno);
        //更新设备表激活状态
        bizPosMachineStatusRecordsMapper.updatePosMachine(termphyno);
        //运行函数
        iBizMerchantService.generateAllPosMerchantRelatedProcedure();
//        // 删除未激活模板数据
//        iAizUnActiveRecordsService.deleteBySn(termphyno);
        return AjaxResult.success();
    }
}
